<template>
    <div class="login-container">
        <div class="login-box">
            <div class="login-title">中医智诊后台管理系统1</div>
            <el-form :model="formData" :rules="rules" ref="formRef">
                <el-form-item prop="username">
                    <el-input v-model="formData.username" placeholder="账号" :prefix-icon="User" @change="handleSubmit" />
                </el-form-item>

                <el-form-item prop="password">
                    <el-input v-model="formData.password" type="password" placeholder="密码" :prefix-icon="Lock"
                        show-password @change="handleSubmit" />
                </el-form-item>

                <el-form-item prop="confirmPassword" v-if="!isLogin">
                    <el-input v-model="formData.confirmPassword" type="password" placeholder="确认密码" :prefix-icon="Lock"
                        show-password @change="handleSubmit" />
                </el-form-item>

                <el-form-item v-if="isLogin">
                    <el-checkbox v-model="formData.rememberMe">记住密码</el-checkbox>
                </el-form-item>

                <el-button type="primary" :loading="loading" class="submit-btn" @click="handleSubmit">
                    {{ isLogin ? '登录' : '注册' }}
                </el-button>

                <div class="switch-action">
                    <a @click="switchMode">{{ isLogin ? '还没有账号？立即注册' : '已有账号？立即登录' }}</a>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const router = useRouter()
const loading = ref(false)
const formRef = ref(null)
const isLogin = ref(true)

const formData = reactive({
    username: 'admin',
    password: '123456',
    confirmPassword: '',
    rememberMe: false
})

const validateConfirmPassword = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请再次输入密码'))
    } else if (value !== formData.password) {
        callback(new Error('两次输入密码不一致'))
    } else {
        callback()
    }
}

const rules = {
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { validator: validateConfirmPassword, trigger: 'blur' }
    ]
}

const switchMode = () => {
    ElMessage.error('不支持注册，只能由管理员添加！')
    return

    isLogin.value = !isLogin.value
    formRef.value?.resetFields()
}

const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        loading.value = true

        if (isLogin.value) {
            // 登录请求
            const res = await request({
                url: '/employee/login',
                method: 'post',
                data: {
                    username: formData.username,
                    password: formData.password,
                }
            })

            // 保存用户信息
            localStorage.setItem('userInfo', JSON.stringify(res.data))

            // 先提示成功
            ElMessage.success('登录成功')

            // 使用 nextTick 确保在 DOM 更新后再跳转
            nextTick(() => {
                router.push('/')
            })
        } else {
            // 注册请求
            await request({
                url: '/employee/register',
                method: 'post',
                data: {
                    username: formData.username,
                    password: formData.password
                }
            })

            ElMessage.success('注册成功')
            isLogin.value = true
            formRef.value.resetFields()
        }
    } catch (error) {
        console.error('登录失败:', error)
    } finally {
        loading.value = false
    }
}
</script>

<style scoped>
.login-container {
    height: 100vh;
    background-image: url('@/assets/images/login-background.jpg');
    background-size: cover;
    background-position: center;
    display: flex;
    justify-content: center;
    align-items: center;
}

.login-box {
    width: 400px;
    padding: 30px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
    text-align: center;
    font-size: 18px;
    color: #333;
    margin-bottom: 30px;
}

:deep(.el-input__wrapper) {
    background-color: #fff;
}

:deep(.el-input__inner) {
    height: 40px;
}

.submit-btn {
    width: 100%;
    height: 40px;
    font-size: 16px;
}

:deep(.el-checkbox__label) {
    color: #606266;
}

.switch-action {
    text-align: center;
    margin-top: 15px;
}

.switch-action a {
    color: #409EFF;
    cursor: pointer;
    text-decoration: none;
}

.switch-action a:hover {
    color: #66b1ff;
}
</style>